package com.zyy.Household_expenditure.controller;


import com.zyy.Household_expenditure.common.result.R;
import com.zyy.Household_expenditure.entity.HomeUser;
import com.zyy.Household_expenditure.service.HomeUserService;
import com.zyy.Household_expenditure.utils.JwtUtils;
import com.zyy.Household_expenditure.utils.MD5;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author TreeRoot
 * @since 2022-10-13
 */
@RestController
@RequestMapping("/user")
@CrossOrigin
@Api(description = "用户接口")
public class HomeUserController {
    @Resource
    private HomeUserService userService;
    //    登录



    @PostMapping("/login")
    @ApiOperation(" 登录")
    public R login(@RequestBody HomeUser user) {
        String token = userService.login(user);
        return R.ok().data("token", token);
    }

//注册
    @PostMapping("/register")
    @ApiOperation(" 注册")
    public R register(@RequestBody HomeUser user) {
     String msg =   userService.register(user);
        return R.ok().data("msg",msg);
    }

    //注册
    @PostMapping("/update")
    @ApiOperation(" 更新")
    public R update(@RequestBody HomeUser user) {
        String msg = null;
        user.setPassword(MD5.encrypt(user.getPassword()));
        boolean b = userService.updateById(user);
        if (b){
           msg ="成功";
        }
        return R.ok().data("msg",msg);
    }

//根据用户id得到用户信息
    @GetMapping("/getOneByid/{id}")
    @ApiOperation("根据id拿用户信息")
    public R getOneByid(@PathVariable String id) {
        HomeUser user = userService.getById(id);
        return R.ok().data("user", user);
    }

//    根据token得到用户信息
    /**
     * 根据request对象获取头部信息，返回用户id
     * 通过用户id得到用户信息  返回 用户信息
     * @param request
     * @return
     */
    @GetMapping("getUserInfoByToken")
    @ApiOperation("根据request对象获取头部信息，返回用户id")
    public R getUserInfoByToken(HttpServletRequest request) {
        // 调用jwt工具类。根据request对象获取头部信息，返回用户id
        //        调数据库 根据用户id获取用户信息
        String id = JwtUtils.getMemberIdByJwtToken(request);
        HomeUser user = userService.getById(id);
        return R.ok().data("userInfo", user);
    }

}

